package org.oschina.zb.platform.localmsg.schedule;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.oschina.zb.platform.core.mybatis.Page;
import org.oschina.zb.platform.localmsg.contants.LocalMessageConstant;
import org.oschina.zb.platform.localmsg.mq.QMessage;
import org.oschina.zb.platform.localmsg.mq.QSender;
import org.oschina.zb.platform.localmsg.mysql.dao.LocalMessageDao;
import org.oschina.zb.platform.localmsg.mysql.entity.LocalMessage;
import org.oschina.zb.platform.localmsg.util.JsonAdapter;
import org.oschina.zb.platform.utils.logger.LoggerUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class LocalMessageScanner {

	private LoggerUtils logger = LoggerUtils.getLogger(LocalMessageScanner.class);

	public final static long FIVE_MINUTES = 5 * 60 * 1000;

	@Resource
	private LocalMessageDao localMessageDao;

	@Resource
	private QSender qSender;

	@SuppressWarnings("unchecked")
//	@Scheduled(fixedDelay = FIVE_MINUTES)
	public void scan() {
		int currentPage = 1;
		int pageSize = 10;
		// 1.分页读取超过相应时间未处理的任务
		Date beforeDate = new Date(System.currentTimeMillis() - FIVE_MINUTES);
		String beforeDateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(beforeDate);
		while (true) {
			Page<LocalMessage> page = localMessageDao.findPageOfUnFinished(beforeDateStr, currentPage++, pageSize);
			List<LocalMessage> list = page.getData();
			logger.info("[成功]-[本地消息表扫描任务]-发现未处理消息:(" + page.getTotalCount() + ")");
			for (LocalMessage localMessage : list) {
				QMessage qMessage = new QMessage();
				qMessage.setId(localMessage.getId());
				qMessage.setType(localMessage.getType());
				try {
					qMessage.setParams(JsonAdapter.json2Object(localMessage.getParams(), Map.class));
				} catch (IOException e) {
					logger.error("[失败]-[本地消息表扫描任务]-[json转换异常]", e);
					continue;
				}
				// 放入队列
				qSender.send(LocalMessageConstant.Q_NAME, qMessage);
			}
			if (list.size() < pageSize) {
				currentPage = 1;
				break;
			}
		}
	}
}
